package com.ztsoft.user.service.dynamic.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztsoft.user.mapper.dynamic.ColumnDescriptionMapper;
import com.ztsoft.user.mapper.dynamic.UserColumnMapper;
import com.ztsoft.user.pojo.entity.dynamic.ColumnDescription;
import com.ztsoft.user.pojo.entity.dynamic.UserColumn;
import com.ztsoft.user.pojo.entity.user.SysUser;
import com.ztsoft.user.pojo.vo.dynamic.CustomColumnVo;
import com.ztsoft.user.service.dynamic.UserColumnService;
import com.ztsoft.user.service.user.SysUserService;
import com.ztsoft.user.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserColumnServiceImpl extends ServiceImpl<UserColumnMapper, UserColumn> implements UserColumnService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ColumnDescriptionMapper columnDescriptionMapper;

    @Override
    public List<ColumnDescription> getUserColumn(String tableCode, String id) {
        return baseMapper.getUserColumn(tableCode, id);
    }

    @Override
    public void removeUserColumn(String tableCode, String id) {
        baseMapper.deletetUserColumn(tableCode, id);
    }

    @Override
    public void saveUserColumn(CustomColumnVo customColumnVo) {
        UserHolder userInfo = sysUserService.getUserInfo();
        SysUser sysUser = userInfo.getSysUser();

        ColumnDescription columnDescription = columnDescriptionMapper.selectById(customColumnVo.getId());

        Date date = new Date(System.currentTimeMillis());
        UserColumn userColumn = new UserColumn();
        BeanUtils.copyProperties(columnDescription, userColumn);
        if (userColumn.getRawId() == null || "".equals(userColumn.getRawId())) {
            userColumn.setRawId(userColumn.getId());
        }
        String id = UUID.randomUUID().toString().replace("-", "");
        userColumn.setCreateTime(date);
        userColumn.setCreateId(sysUser.getUserId());
        userColumn.setModifyTime(date);
        userColumn.setId(id);
        this.save(userColumn);

        BeanUtils.copyProperties(customColumnVo, userColumn);
        userColumn.setId(id);
        this.updateById(userColumn);
    }

    @Override
    public void updateUserColumn(CustomColumnVo customColumnVo) {
        Date date = new Date(System.currentTimeMillis());
        UserColumn userColumn = new UserColumn();
        BeanUtils.copyProperties(customColumnVo, userColumn);
        userColumn.setModifyTime(date);
        this.updateById(userColumn);
    }
}
